package com.aofeng.hybridwork.android.task;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.StrictMode;

import com.aofeng.hybrid.activity.HybridActivity;
import com.aofeng.hybrid.android.NativeBaseMethod;
import com.aofeng.hybrid.service.EntityService;
import com.aofeng.hybrid.service.RestService;
import com.aofeng.hybrid.service.SqlService;
import com.aofeng.hybridwork.application.HybridApplication;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 上传安检计划异步任务
 * Created by LGY on 2016-08-25.
 */
public class UploadAsyncTask extends AsyncTask<String, String, Boolean> {
    HybridActivity hybridActivity;

    private static Map<String, String> links = new HashMap<String, String>();

    static
    {
        links.put("f_meters", "t_check_paper_meter");
        links.put("f_plumbs", "t_check_paper_plumb");
        links.put("f_inner_plumbs", "t_check_paper_innerplumb");
        links.put("f_defects", "t_check_paper_defect");
        links.put("f_counters", "t_check_paper_counter");
        links.put("f_alarms", "t_check_paper_alarm");
        links.put("f_cookers", "t_check_paper_cooker");
        links.put("f_valves", "t_check_paper_valve");
        links.put("f_furnaces", "t_check_paper_furnace");
        links.put("f_heaters", "t_check_paper_heater");
        links.put("f_devices", "t_check_paper_device");
    }

    public UploadAsyncTask(HybridActivity hybridActivity) {
        this.hybridActivity = hybridActivity;
    }

    @Override
    /**
     * params:
     * 下载的url
     */
    protected Boolean doInBackground(String... params) {
        try {
            JSONObject paper = new JSONObject(params[2]);
            publishProgress(new String[]{ 0 + "", "保存安检单......"});
            SavePaperTask.savePaper(paper, params[0], params[1], hybridActivity, false);
            publishProgress(new String[]{ 5 + "", "上传开始......"});
            //JSONObject paper = FetchPaperTask.getPaper(params[0], params[1], hybridActivity);
            publishProgress(new String[]{ 10 + "", "上传图片开始......"});
            Map<String,String> map = new HashMap<>();
            JSONArray devices = new JSONArray();
            getPicsAndAdjustCheckboxes(paper, map, devices);
            int n = map.size();
            int i = 0;
            for(String key :map.keySet()) {
                if(!upload(key, map.get(key)))
                    return false;
                i++;
                publishProgress(new String[]{ (10 + ((70*i)/n)) + "", "上传图片" + i + "完成"});
            }
            paper.put("f_repaired", "未修");
            paper.put("f_repaired_uploaded", "未传");
            // upload data
            RestService rs = new RestService(hybridActivity);
            JSONObject joRequest = new JSONObject();
            joRequest.put("action", "post");
            joRequest.put("url", HybridApplication.LOGIC_SERVICE_URL + URLEncoder.encode("上传安检单", "UTF-8"));
            JSONObject data = new JSONObject();
            data.put("paper", paper);
            data.put("devices", devices);
            JSONObject row = new JSONObject();
            row.put("data", data);
            joRequest.put("data", row);
            rs.execute(joRequest);
            //修改客户端状态
            SqlService ss = new SqlService(hybridActivity);
            ss.run("update t_check_plan_item set f_upload_state='已传' where id = '" + params[0] + "'");
            publishProgress(new String[]{ 100 + "", "上传成功。"});
            return true;
        } catch(Exception e) {
            return false;
        }
    }

    public boolean findIfVerified(String f_check_item_id) throws Exception {
        RestService rs = new RestService(hybridActivity);
        JSONObject json = new JSONObject();
        json.put("action", "post");
        json.put("url", HybridApplication.SQL_SERVICE_URL + URLEncoder.encode("计划项是否已经审核", "UTF-8"));
        json.put("data", "{\"data\":{\"f_check_item_id\":\"" + f_check_item_id + "\"}}");
        String verified = ((JSONArray) rs.execute(json)).getJSONObject(0).getString("f_approved");
        return verified.equals("已审核");
    }

    private boolean upload(String key, String fileName) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        try
        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext httpContext = new BasicHttpContext();
            String url = HybridApplication.BASE_URL + "/db/savefile" + "?FileName="
                    + URLEncoder.encode(key) + "&BlobId="
                    + URLEncoder.encode(key)
                    + "&EntityName=t_blob";
            HttpPost httpPost = new HttpPost(url);
            FileEntity entity = new FileEntity(new File(fileName), "binary/octet-stream");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost, httpContext);
            return response.getStatusLine().getStatusCode() == 200;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    private void getPicsAndAdjustCheckboxes(JSONObject paper, Map<String,String> map, JSONArray devices) throws Exception {
        Iterator<String> itr = paper.keys();
        String[] keys = new String[paper.length()];
        int i=0;
        while(itr.hasNext())
            keys[i++] = itr.next();

        for(String key : keys) {
            if(!paper.isNull(key)) {
                if(key.endsWith("_path")) {
                    String value = paper.getString(key);
                    if(value.endsWith("nopic.png"))
                        paper.put(key, null);
                    else {
                        if(value.startsWith("file://"))
                            value = value.substring(7);
                        int pos = value.lastIndexOf("/") + 1;
                        int pos2 = value.indexOf("?");
                        if(pos2 == -1)
                            pos2 = value.length();
                        String k = value.substring(pos, pos2);
                        paper.put(key, k);
                        map.put(k, value.substring(0, pos2));
                    }
                } else {
                    Object obj = paper.get(key);
                    if(obj instanceof  JSONArray) {
                        JSONArray array = (JSONArray) obj;
                        for(i=0; i< array.length(); i++) {
                            JSONObject row = array.getJSONObject(i);
                            getPicsAndAdjustCheckboxes(row, map, devices);
                            String entity = links.get(key);
                            row.put("EntityType", entity);
                            devices.put(row);
                        }
                        paper.remove(key);
                    } else {
                        if(key.equals("id") || key.equals("f_paper_id"))
                            paper.remove(key);
                        if(obj.toString().equals("true") || obj.toString().equals("false"))
                            paper.put(key, obj.toString());
                    }
               }
            }
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        hybridActivity.createProgressDialog(ProgressDialog.STYLE_SPINNER);
    }

    @Override
    protected void onPostExecute(Boolean flag) {
        super.onPostExecute(flag);
        hybridActivity.closeProgress();
        if(flag) {
                NativeBaseMethod.alert(hybridActivity.mWebView, "上传成功！");
        }
        else
            NativeBaseMethod.alert(hybridActivity.mWebView, "上传失败！");
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        int progress = Integer.parseInt(values[0]);
        hybridActivity.setProgress(progress, values[1]);
    }
}
